package com.kaili.tms.controller.web.v1;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import com.kaili.common.aop.SpringContextHolder;
import com.kaili.common.response.ResponseData;
import com.kaili.tms.config.BaseImport;
import com.kaili.tms.config.Tools;
import com.kaili.tms.exception.ExcelException;
import com.kaili.tms.export.ExportRespones;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("import")
@Api(tags = "导入服务", description = "数据导入服务")
public class BaseImportController extends BaseController {
    @RequestMapping("/upload")
    @ApiOperation(value = "导入数据", notes = "根据指定的类型导入相关的数据")
    public Object upload(@RequestParam("file") MultipartFile file, @RequestParam("type") String type) throws ExcelException {
        if (!file.isEmpty() && !Tools.isEmpty(type)) {
            List<String> list = SpringContextHolder.getBeansName(BaseImport.class);
            for (String aList : list) {
                if (aList.endsWith(type)) {
                    try {
                        Class cls = Class.forName(aList);
                        BaseImport baseImport = (BaseImport) SpringContextHolder.getBean(cls);
                        try {
                            baseImport.doAnalyze(file.getInputStream());
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new ExcelException(ExportRespones.FILE_ERROR);
                        }
                        Map ret = new HashMap<String, Object>();
                        ret.put("data", baseImport.getData());
                        ret.put("size", baseImport.getSize());
                        ret.put("errSize", baseImport.getErrSize());
                        if (baseImport.getErrSize() > 0) {
                            Workbook workbook = ExcelExportUtil.exportExcel(baseImport.getExportParams(), baseImport.getCls(), baseImport.getErrData());
                            if (workbook != null) {
                                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                                workbook.write(bout);
                                bout.flush();
                                getSession().setAttribute(cls.toString(), bout.toByteArray());
                                bout.close();
                                workbook.close();
                            }
                        }
                        return ret;
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        throw new ExcelException(ExportRespones.CLASS_ERROR);
                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new ExcelException(ExportRespones.FILE_ERROR);
                    }
                }
            }
        }
        return new ResponseData(ExportRespones.FILE_ERROR);
    }

    @GetMapping("getError")
    @ApiOperation(value = "根据指定类型导入数据中数据异常项", notes = "根据指定类型下载导入环境异常数据,异常数据只缓存20分钟,前端做好提示工作!")
    public void getErrorFile(@RequestParam("type") String type) throws ExcelException {
        if (!Tools.isEmpty(type)) {
            List<String> list = SpringContextHolder.getBeansName(BaseImport.class);
            for (String aList : list) {
                if (aList.endsWith(type)) {
                    try {
                        Class cls = Class.forName(aList);
                        byte[] data = (byte[]) getSession().getAttribute(cls.toString());
                        if (data == null) {
                            throw new ExcelException(ExportRespones.FILE_NOT_EXIST);
                        }
                        response.setHeader("content-disposition", "attachment;filename=download.xlsx");
                        OutputStream out = response.getOutputStream();
                        out.write(data);
                        out.flush();
                        out.close();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        throw new ExcelException(ExportRespones.CLASS_ERROR);
                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new ExcelException(ExportRespones.OUT_ERROR);
                    }
                }
            }
        }
    }
}
